<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\library\Yunding as YdLib;
use app\common\library\Reserve as ReserveLib;
use app\admin\model\Setting;
use Carbon\Carbon;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Room extends Backend
{

    /**
     * Room模型对象
     * @var \app\admin\model\Room
     */
    protected $model = null;

    protected $selectpageFields = ['id','room_name','store_id','store_name'];

    public function _initialize()
    {
        parent::_initialize();
        
        $this->model = new \app\admin\model\Room;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model->with('store')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function rentTime()
    {
        $id = $this->request->get('id');
        $room = $this->model->where('id', $id)->find();
        if ($this->request->isPost()) {
            $room->rent_time = $this->request->post('rent_time');
            $room->save();

            $this->success("保存成功");
        }
        $this->view->assign('row', $room);
        return $this->view->fetch();
    }

    public function previewTime()
    {
        $id = $this->request->get('id');
        $room = $this->model->where('id', $id)->find();
        $this->view->assign('row', $room);
        return $this->view->fetch();
    }

    public function ajaxGetPills()
    {
        $rentPills = [];
        if ($this->request->isAjax()) {
          $id = $this->request->post('id');
          $curDate = $this->request->post('date', date('Y-m-d'));
          $curDateParse = Carbon::parse($curDate);

          $room = $this->model->where('id', $id)->find();

          $reserveLib = new ReserveLib();
          $rentPills = $reserveLib->getRoomPills($room, $curDate);

          foreach ($rentPills as &$pill) {
              if (!isset($pill['is_open'])) {
                  $pill['is_open'] = '1';
              }
          }
          unset($pill);
          $this->success("", '', $rentPills);
    
        }
    }

    public function ajaxGetHomeId()
    {
        $data = ['homeid' => ''];
        if ($this->request->isAjax()) {
            $uuid = $this->request->post('uuid', '');
            if (empty($uuid)) {
                $this->error('云丁uuid不能为空');
            }
            $ydLib = new YdLib();
            $data['homeid'] = $ydLib->searchHomeid($uuid);
            if (empty($data['homeid'])) {
                $this->error('没有找到对应的homeid，请确认uuid是否输入正确');
            }
            $this->success("", '', $data);
        }
    
    }

    public function ajaxGetPreview()
    {
        $data = [];
        if ($this->request->isAjax()) {
          $id = $this->request->post('id');
          $date = $this->request->post('date', date('Y-m-d'));
          if (empty($date)) {
              $date = date('Y-m-d');
          }
          $dateParse = Carbon::parse($date);
          $startDate = $dateParse->startOfMonth()->toDateString();
          $endDate = $dateParse->endOfMonth()->toDateString();

          $room = $this->model->where('id', $id)->find();
          $rentPills = empty($room->rent_time) ? [] : json_decode($room->rent_time, true);
          $weekRentPills = empty($room->week_rent_time) ? [] : json_decode($room->week_rent_time, true);

          $dateRentPills = empty($room->date_rent_time) ? [] : json_decode($room->date_rent_time, true);
          $dateSetting = empty($room->date_setting) ? [] : json_decode($room->date_setting, true);
          
          for($s = 0; $s < 31; $s++) {
              $startDateParse = Carbon::parse($startDate);
              $curDate = $startDateParse->addDays($s)->toDateString();
              $curDateParse = Carbon::parse($curDate);
              // 生成当天的pill
              $rentPills = empty($room->rent_time) ? [] : json_decode($room->rent_time, true);

              $dayOfWeek = 'week' . $curDateParse->dayOfWeek;
              if (!empty($weekRentPills[$dayOfWeek])) {
                  $rentPills = $weekRentPills[$dayOfWeek];
              }

              if (!empty($dateSetting)) {
                  $open = $dateSetting['open'];
                  if ($curDate >= $dateSetting['date1'] && $curDate <= $dateSetting['date2']) {
                      if ($open === '0') {
                          $rentPills = [];
                      } else {
                          $rentPills = $dateRentPills;
                      }
                  }
              }
              $calendar = ['months' => [$curDateParse->format('m')], 'days' => [$curDateParse->format('d')], 'things' => '', 'status' => '', ];
              if (!empty($rentPills)) {
                  $start = '';
                  $end = '';
                  $things = [];
                  foreach ($rentPills as $pill) {
                      // 得到这个pill的完整的开始和结束时间，包括的年月日
                      $pillStart = $curDate . ' ' . $pill['start'];
                      $pillEnd = $curDate . ' ' . $pill['end'];
                      // echo 'pillStart => ' . $pillStart . "---" . $pillEnd . '<br />';
                      if (empty($start)) {
                          $start = $pillStart;
                      }
                      if (empty($end)) {
                          $end = $pillEnd;
                      }
                      // echo 'start =>' . $start . "---" . $end . '<br />';
                      // 非一样时间时，计算相差时间是否为30分钟
                      if ($start != $pillStart) {
                          $tmp1X = strtotime($end);
                          $tmp2X = strtotime($pillEnd);
                          
                          // echo $tmp1X . "---" . $tmp2X . '<br />';
                          $diffX = $tmp2X - $tmp1X;
                          if ($diffX != 1800) {
                              // echo 'diff <> 1800 =>' . $end . "---" . $pillEnd . '<br />';
                              $things[] = date('H:i', strtotime($start)) . '-' . date('H:i', strtotime($end));
                              $start = $pillStart;
                              $end = $pillEnd;
                          } else {
                              // echo 'diff = 1800 =>' . $end . "---" . $pillEnd . '<br />';
                              $end = $pillEnd;
                          }
                      }
                      // echo "******************************<br />";
                  }
                  $things[] = date('H:i', strtotime($start)) . '-' . date('H:i', strtotime($end));
                  $calendar['things'] = '开放时段:' . implode(",", $things);
                  $calendar['status'] = '教室开放';
              } else {
                  $calendar['things'] = '教室关闭';
                  $calendar['status'] = '教室关闭';
              }

              $data[] = $calendar;
              if ($curDate == $endDate) {
                  break;
              }

          }
          $this->success("", '', $data);

        }
    
    }

    public function saveRentTime()
    {
        if ($this->request->isAjax()) {
            $roomId = $this->request->post('id', 0);
            $saveType = $this->request->post('save_type', '');
            if (!$saveType) {
              $this->error("缺少保存的类型");
            }
            $room = $this->model->where('id', $roomId)->find();
            if ($saveType === 'global') {
                $rentTime = $this->request->post('rent_time', '');
                if (!$rentTime) {
                  $this->error("租用时段为空");
                }
                $room->rent_time = $rentTime; 
            }
            // 如果星期设置
            if ($saveType === 'week') {
                $weekRentTime = $this->request->post('week_rent_time', '');
                if (!$weekRentTime) {
                  $this->error("租用时段为空");
                }
                $room->week_rent_time = $weekRentTime;
            }
            if ($saveType === 'date') {
                $dateRentTime = $this->request->post('date_rent_time', '');
                $dateSetting = $this->request->post('date_setting', '');
                if (!$dateRentTime) {
                  $this->error("租用时段为空");
                }
                if (!$dateSetting) {
                  $this->error("日期设置为空");
                }
                $room->date_rent_time = $dateRentTime;
                $room->date_setting = $dateSetting;
            }
            $room->save();
            $this->success("保存成功");
        }
    }


    public function ajaxGetRoom()
    {
        if ($this->request->isAjax()) {
            $withoutAll = $this->request->get('withoutall', 0);
            $storeId = $this->request->get('store_id');
            if (!$withoutAll) {
                $data[] = [
                    'name' => '全部教室',
                    'value' => 0,
                ];
            }

            if (0 == $storeId) {
            } else {
                $rows = $this->model->where('store_id', $storeId)->select();
                foreach ($rows as $row) {
                    $data[] = [
                        "name" => $row->room_name,
                        "value" => $row->id
                    ];
                }
            }
            $this->success('', '', $data);
        }
        $this->error('error');
    }

    public function ajaxCopy()
    {
        $roomId = $this->request->get('id');
        $room = \app\admin\model\Room::get($roomId);

        $properties = $room->toArray();

        unset($properties['id']);
        $properties['room_name'] = $properties['room_name'] . '(复制)';
        unset($properties['yunding_homeid']);
        unset($properties['yunding_uuid']);

        \app\admin\model\Room::create($properties);

        $this->result('', 1, '复制成功');
    }

    protected function selectpage()
    {
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 999999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 999999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                $searchfield = str_replace(',', $logic, $searchfield);
                $word = array_filter(array_unique($word));
                if (count($word) == 1) {
                    $query->where($searchfield, "like", "%" . reset($word) . "%");
                } else {
                    $query->where(function ($query) use ($word, $searchfield) {
                        foreach ($word as $index => $item) {
                            $query->whereOr(function ($query) use ($item, $searchfield) {
                                $query->where($searchfield, "like", "%{$item}%");
                            });
                        }
                    });
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $this->model->where($where)->where('status', 'normal')->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }

            $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);

            //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
            if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
                $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
                //修复自定义data-primary-key为字符串内容时，给排序字段添加上引号
                $primaryvalue = array_map(function ($value) {
                    return '\'' . $value . '\'';
                }, $primaryvalue);

                $primaryvalue = implode(',', $primaryvalue);

                $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
            } else {
                $this->model->order($order);
            }

            $datalist = $this->model->where($where)
                ->where('status', 'normal')
                ->with('store')
                ->page($page, $pagesize)
                ->select();

            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                if ($this->selectpageFields == '*') {
                    $result = [
                        $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                        $field      => isset($item[$field]) ? $item[$field] : '',
                    ];
                } else {
                    $result = [
                        $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                        'store_name' => $item->store->store_name,
                        'room_name' => $item->room_name,
                    ];
                }
                $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
                $list[] = $result;
            }
            if ($istree && !$primaryvalue) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }

}
